package it.fantacalcio.spring.service;

import it.fantacalcio.model.Role;
import it.fantacalcio.hibernate.dao.RoleDAO;
import it.fantacalcio.hibernate.sessionfactory.HibernateSessionFactory;

import java.util.List;

import org.hibernate.Transaction;

public class RoleServiceImpl implements RoleService {
	
	private RoleDAO roleDAO;
	
	public RoleDAO getRoleDAO() {
		return roleDAO;
	}

	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}
	
	//----------------------------------------------------------------------------------

	@Override
	public int salva(Role role) throws Exception {
		if(role==null){
			return -1;
		}
		try{
			Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
				roleDAO.save(role);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
			return -2;
		}
		return 1;
	}
	
	@Override
	public int cancella(Role role) throws Exception {
		if(role==null || role.getId()<1){
			return -1;
		}
		try{
			Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
				roleDAO.delete(role);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
			return -2;
		}
		return 1;
	}
	
	@Override
	public int modifica(Role role) throws Exception {
		if(role==null || role.getId()<1){
			return -1;
		}
		try{
			Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
				roleDAO.update(role);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
			return -2;
		}
		return 1;
	}
	
	@Override
	public Role get(Long id) throws Exception {
		if(id<1){
			return null;
		}
		Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
			Role role = roleDAO.get(id);
		tx.commit();
		return role;
	}

	@Override
	public List<Role> list() throws Exception {
		Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
			List<Role> result=roleDAO.list();
		tx.commit();
		return result;
	}
	
	@Override
	public List<Role> findByExample(Role role) throws Exception {
		if(role==null){
			return null;
		}
		Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
			List<Role> result=roleDAO.findByExample(role);
		tx.commit();
		return result;
	}

}
